package com.example.springbootinit.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springbootinit.domain.User;
import com.example.springbootinit.service.UserService;
import com.example.springbootinit.mapper.UserMapper;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
* @author sxt-xy
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-03-18 21:26:47
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{
    //@Autowired
    //private UserMapper userMapper;   ServiceImpl<UserMapper, User>已经关联了UserMapper，所以不需要再显式添加依赖



    @Override
    public Optional<User> selectById(Long id) {
        // MyBatis-Plus的selectById返回null表示无数据
        User user = this.getBaseMapper().selectById(id);
        return Optional.ofNullable(user);
    }


    @Override
    public Optional<List<User>> selectList() {
        return Optional.ofNullable(this.getBaseMapper().selectList(null));
    }

    @Override
    public boolean insert(User user) {
        try {
            return this.getBaseMapper().insert(user) == 1;
        } catch (DuplicateKeyException e) {
            // 处理重复 email 的情况
            System.out.println("Email 已存在，插入失败：" + user.getEmail());
            return false;
        }
    }

}
